
//
//  JQUMSocialService.m
//  JQUMSocialService
//
//  Created by JQZ on 2018/1/19.
//  Copyright © 2018年 JQ. All rights reserved.
//

#import "JQUMSocialService.h"

#ifdef DEBUG
#define DLog(fmt, ...) NSLog(fmt, ##__VA_ARGS__);
#else
#define DLog(...)
#endif

// 没设置友盟appkey
#define TIP_UM_SOCIAL_APPKEY @"请先设置友盟appkey"

@interface JQUMSocialService()

@property(nonatomic, assign) UMSocialPlatformType curPlatformType;
@property(nonatomic, strong) UMSocialRequestCompletionHandler completionBlock;
@property(nonatomic, strong) NSMutableDictionary *platformMap;

@end

@implementation JQUMSocialService

JQ_EXPORT_SERVICE(JQUMSocialService)

#pragma mark - #JQUMSocialService init
- (id)init {
    if (self = [super init]){
        self.curPlatformType = UMSocialPlatformType_UnKnown;
    }
    return self;
}

#pragma mark - #UIApplicationDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // 友盟社交初始化
    DLog(@"JQUMSocialService初始化");
    [self initUMSocial:launchOptions];
    
    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    if (self.curPlatformType != UMSocialPlatformType_UnKnown){
        NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:NSLocalizedString(@"Operation is cancel", @"操作取消") forKey:NSLocalizedDescriptionKey];
        NSError *error = [NSError errorWithDomain:@"UMSocialPlatformErrorDomain" code:UMSocialPlatformErrorType_Cancel userInfo:errorMessage];
        self.completionBlock?self.completionBlock(nil, error):nil;
        self.curPlatformType = UMSocialPlatformType_UnKnown;
    }
}

// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url
                                                sourceApplication:sourceApplication
                                                       annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

// 仅支持iOS9以上系统，iOS8及以下系统不会回调
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url options:options];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

// 支持目前所有iOS系统
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

#pragma mark - #Public
- (void)setPlaform:(UMSocialPlatformType)platformType
            appKey:(NSString *)appKey
         appSecret:(NSString *)appSecret
       redirectURL:(NSString *)redirectURL
{
    UMSocialPlatformConfig *config = [[UMSocialPlatformConfig alloc] init];
    config.appKey = appKey;
    config.appSecret = appSecret;
    config.redirectURL = redirectURL;
    [self.platformMap setObject:config forKey:@(platformType)];
}

- (void)shareToPlatform:(UMSocialPlatformType)platformType
          messageObject:(UMSocialMessageObject *)messageObject
  currentViewController:(id)currentViewController
             completion:(UMSocialRequestCompletionHandler)completion
{
    self.curPlatformType = platformType;
    self.completionBlock = completion;
    [[UMSocialManager defaultManager] shareToPlatform:platformType
                     messageObject:messageObject
             currentViewController:currentViewController
                        completion:^(id result, NSError *error) {
                            self.curPlatformType = UMSocialPlatformType_UnKnown;
                            self.completionBlock = nil;
                            completion?completion(result, error):nil;
                        }];
}

- (void)cancelAuthWithPlatform:(UMSocialPlatformType)platformType
                    completion:(UMSocialRequestCompletionHandler)completion
{
    [[UMSocialManager defaultManager] cancelAuthWithPlatform:platformType completion:completion];
}

- (void)getUserInfoWithPlatform:(UMSocialPlatformType)platformType
          currentViewController:(id)currentViewController
                     completion:(UMSocialRequestCompletionHandler)completion
{
    self.curPlatformType = platformType;
    self.completionBlock = completion;
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:platformType
                     currentViewController:currentViewController
                                completion:^(id result, NSError *error) {
                                    completion?completion(result, error):nil;
                                    self.curPlatformType = UMSocialPlatformType_UnKnown;
                                    self.completionBlock = nil;
                                }];
}

#pragma mark - #Private
- (void)initUMSocial:(NSDictionary *)launchOptions {
    
    NSAssert(self.umSocialAppkey, TIP_UM_SOCIAL_APPKEY);
    
    /* 打开调试日志 */
#ifdef DEBUG
    [[UMSocialManager defaultManager] openLog:YES];
#else
    [[UMSocialManager defaultManager] openLog:NO];
#endif
    
    /* 设置友盟appkey */
    if (self.umSocialAppkey) {
        [[UMSocialManager defaultManager] setUmSocialAppkey:self.umSocialAppkey];
    }
    else {
        DLog(TIP_UM_SOCIAL_APPKEY);
    }
    
    /* 设置友盟appSecret */
    if (self.umSocialAppSecret) {
        [[UMSocialManager defaultManager] setUmSocialAppSecret:self.umSocialAppSecret];
    }
    
    [self configUSharePlatforms];
    [self confitUShareSettings];
}

- (void)configUSharePlatforms
{
    [self.platformMap enumerateKeysAndObjectsUsingBlock:^(NSNumber *platformType,
                                                          UMSocialPlatformConfig *config,
                                                          BOOL * _Nonnull stop) {
        [[UMSocialManager defaultManager] setPlaform:platformType.integerValue
                                              appKey:config.appKey
                                           appSecret:config.appSecret
                                         redirectURL:config.redirectURL];
    }];
}

- (void)confitUShareSettings
{
    /*
     * 打开图片水印
     */
    [UMSocialGlobal shareInstance].isUsingWaterMark = NO;
    
    /*
     * 关闭强制验证https，可允许http图片分享，但需要在info.plist设置安全域名
     */
    [UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;
}

#pragma mark - #Getter
- (NSMutableDictionary *)platformMap {
    if (!_platformMap) {
        _platformMap = [[NSMutableDictionary alloc] init];
    }
    return _platformMap;
}

@end
